/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dspot.declex.actions;

/**
 * @since 2021-07-17
 */

import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.event.intentagent.IntentAgent;
import ohos.event.intentagent.IntentAgentConstant;
import ohos.event.intentagent.IntentAgentHelper;
import ohos.event.intentagent.IntentAgentInfo;
import ohos.event.notification.NotificationActionButton;
import ohos.event.notification.NotificationConstant;
import ohos.event.notification.NotificationHelper;
import ohos.event.notification.NotificationRequest;
import ohos.event.notification.NotificationUserInput;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;
import ohos.rpc.RemoteException;

import com.dspot.declex.annotation.action.ActionFor;
import com.dspot.declex.annotation.action.FormattedExpression;
import com.dspot.declex.annotation.action.StopOn;

import org.ohosannotations.annotations.RootContext;
import org.ohosannotations.annotations.SystemService;
import org.ohosannotations.api.BackgroundExecutor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 通知行动持有人
 * An Action that represents how a persistent notification is to be presented to
 * the user using the {@link NotificationHelper}.
 *
 * <div class="special reference">
 * <h3>Developer Guides</h3>
 * <p>For a guide to creating notifications, read the
 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>
 * developer guide.</p>
 * </div>
 *
 * @author Administrator
 * @date 2021/07/27
 */

@ActionFor("Notification")
public class NotificationActionHolder {

    /**
     * 构建器
     */
    NotificationRequest.NotificationNormalContent builder; //NotificationCompat.Builder

    /**
     * 上下文
     */
    @RootContext
    Context context;

    /**
     * 经理
     */
    @SystemService
    NotificationHelper manager; // NotificationManager manager;

    /**
     * 取消之前的
     */
    private boolean cancelPrevious = true;

    /**
     * 通知id
     */
    private int notificationId;
    /**
     * 等待大图标加载
     */
    private String pendingLargeIconLoad;

    /**
     * 所示
     */
    private Runnable Shown;

    /**
     * 初始化
     *
     * @param notificationId An identifier for this notification unique within your
     * application.
     */
    void init(int notificationId) {
        builder = new NotificationRequest.NotificationNormalContent();
        this.notificationId = notificationId;
    }

    /**
     * 构建
     *
     * @param Shown <i><b>(default)</b></i> This Action Selector will be executed when the Notification is shown
     * with the NotificationManager
     */
    void build(final Runnable Shown) {
        if (cancelPrevious) {
            try {
                manager.cancelNotification(notificationId);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        this.Shown = Shown;
    };

    /**
     * 执行
     */
    void execute() {

        final Runnable execute = new Runnable() {

            @Override
            public void run() {
//                manager.notify(notificationId, builder.setNotificationId(notificationId));
                if (Shown != null) Shown.run();
            }
        };

        if (pendingLargeIconLoad != null) {
            BackgroundExecutor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
//                        Bitmap bitmap = Picasso.with(context).load(pendingLargeIconLoad).get();
//                        pendingLargeIconLoad = null;
//                        builder.setLargeIcon(bitmap);
                        PixelMap pixelMap = getPixMap();
                        NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(
                            builder);
                        NotificationRequest notificationRequest = new NotificationRequest(100);
                        notificationRequest.setContent(notificationContent);
                        IntentAgent intentAgent = setIntentAgent();
                        NotificationActionButton actionButton = new NotificationActionButton.Builder(pixelMap, "",
                            intentAgent).addNotificationUserInput(
                            new NotificationUserInput.Builder("QUICK_NOTIFICATION_REPLY").setTag("input text").build())
                            .setSemanticActionButton(NotificationConstant.SemanticActionButton.ARCHIVE_ACTION_BUTTON)
                            .setAutoCreatedReplies(false)
                            .setContextDependent(true)
                            .build();
                        notificationRequest.addActionButton(actionButton);
                        manager.publishNotification(notificationRequest);
                    } catch ( RemoteException ignored) {}
                    EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());
                    handler.postSyncTask(execute);
//                    Handler mainHandler = new Handler(context.getMainLooper());
//                    mainHandler.post(execute);
                }
            });
        } else {
            execute.run();
        }


    }

    /**
     * 得到照片地图
     *
     * @return {@link PixelMap}
     */
    private PixelMap getPixMap() {
        PixelMap pixelMap = null;
        try {
            RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry("declex_actions/resources/rawfile/" + "icon.png");
            Resource resource = rawFileEntry.openRawFile();
            ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
            ImageSource imageSource = ImageSource.create(resource, srcOpts);
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            decodingOptions.desiredSize = new Size(0, 0);
            decodingOptions.desiredRegion = new Rect(0, 0, 0, 0);
            decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
            pixelMap = imageSource.createPixelmap(decodingOptions);
        } catch (IOException e) {
        }
        return pixelMap;
    }

    /**
     * 意图设置代理
     *
     * @return {@link IntentAgent}
     */
    private IntentAgent setIntentAgent() {
        Intent intent = new Intent();
        intent.setAction("SEND_MESSAGE");
        List<Intent> intentList = new ArrayList<>();
        intentList.add(intent);

        IntentAgentInfo intentAgentInfo = new IntentAgentInfo(200,
            IntentAgentConstant.OperationType.SEND_COMMON_EVENT, IntentAgentConstant.Flags.CANCEL_PRESENT_FLAG,
            intentList, null);
        return IntentAgentHelper.getIntentAgent(context, intentAgentInfo);
    }

    /**
     * 构建器
     *
     * @return Builder layer to access the underlying Notifications Builder object
     * @see NotificationRequest.NotificationNormalContent Notifications Builder
     */
    @StopOn("build")
    public NotificationRequest.NotificationNormalContent builder() {
        return this.builder;
    }

    /**
     * 内容标题
     *
     * @param contentTitle 内容标题
     * @return {@link NotificationActionHolder}
     */
    public NotificationActionHolder contentTitle(@FormattedExpression String contentTitle) {
        builder.setTitle(contentTitle);
        return this;
    }

    /**
     * 内容的文本
     * Set the second line of text in the platform notification template.
     *
     * @param contentText 内容的文本
     * @return {@link NotificationActionHolder}
     */
    public NotificationActionHolder contentText(@FormattedExpression String contentText) {
        builder.setText(contentText);
        return this;
    }

}

